package com.example.demo.interpolation;

public class Lagrange {

    public static void main(String[] args) {
        double[] x = {1, 2, 3};
        double[] y = {4.2, 5.5, 6.8};
        double result = lglrchzh(x, y, 2.5);
        System.out.println("lglrchzh = " + result);
    }


    /**
     * 拉格朗日插值
     *
     * @param x x坐标数组
     * @param y y坐标数组
     * @param X 需要计算的x坐标值
     * @return 插值结果
     */
    public static double lglrchzh(double[] x, double[] y, double X) {
        int n = x.length - 1;
        double Y = 0;
        for (int k = 0; k <= n; k++) {
            double t = 1;
            for (int j = 0; j <= n; j++) {
                if (j == k) {
                    j = k + 1;
                    if (j > n) {
                        break;
                    }
                }
                t *= (X - x[j]) / (x[k] - x[j]);
            }
            Y = Y + t * y[k];
        }
        return Y;
    }
}

